package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.List;

@RestController
@RequestMapping("/setmeal")
public class SetmealController {
    @Autowired
    private JedisPool jedisPool;

    @Reference
    private SetmealService setmealService;

    @RequestMapping("/getSetmeal")
    public Result getSetmeal() {
        String allSetmealJson = jedisPool.getResource().get("allSetmeal");
        try {
            if(allSetmealJson == null){
                List<Setmeal> setmeals = setmealService.findAll();
                String setmealsJson = JSON.toJSONString(setmeals);
                jedisPool.getResource().set("allSetmeal", setmealsJson);
                return new Result(true, MessageConstant.QUERY_SETMEAL_SUCCESS,setmeals);
            }else{
                JSONArray allSetmealText = JSONArray.parseArray(allSetmealJson);
                List<Setmeal> setmeals = JSONObject.parseArray(allSetmealText.toJSONString(), Setmeal.class);
                return new Result(true, MessageConstant.QUERY_SETMEAL_SUCCESS,setmeals);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.QUERY_SETMEAL_FAIL);
        }
    }

    @RequestMapping("/findById")
    public Result findById(Integer id) {
        try {
            return new Result(true, MessageConstant.QUERY_SETMEAL_SUCCESS,setmealService.findById(id));
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.QUERY_SETMEAL_FAIL);
        }
    }
}
